﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Net;

namespace Wicresoft.SMS.Common
{
    public class CILHelper : ICILHelper
    {
        private string Server = "";

        private string ConnectString;

        public CILHelper(string _CILServer)
        {
            this.Server = _CILServer;
        }

        //public CILHelper(string _ConnectString)
        //{
        //    this.ConnectString = _ConnectString;
        //}

        public CILHelper(string _CILServer, string _ConnectString)
        {
            this.Server = _CILServer;
            this.ConnectString = _ConnectString;
        }

        public bool ValidationUser(string username, string pwd)
        {
            return CILAuthenticate(this.Server, username, pwd);
        }

        // Exceptions:
        //   System.ObjectDisposedException:
        //   System.DirectoryServices.Protocols.LdapException:
        //   System.InvalidOperationException:
        private bool CILAuthenticate(string server, string username, string password)
        {
            LdapDirectoryIdentifier ldapID = new LdapDirectoryIdentifier(server);
            NetworkCredential credential = new NetworkCredential(username, password);
            using (LdapConnection ldapCn = new LdapConnection(ldapID, credential, AuthType.Basic))
            {
                try
                {
                    ldapCn.Bind();
                }
                catch (LdapException e)
                {
                    // if error code equals to 49, it means the network credential is invalid.
                    if (e.ErrorCode == 49)
                        return false;
                    else
                        throw;
                }
            }

            return true;
        }

        public C_evw_Employee GetUserInfoByCIL(string cilname)
        {
            try
            {
                using (var hrdb = new HResourceEntities(this.ConnectString))
                {
                    var user = hrdb.C_evw_Employee.FirstOrDefault(p => p.CILX500 == cilname);
                    return user;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("GetUserInfoByCIL" + ex.Message);
                return null;
            }
           
        }
    }
}
